// Alert types and interfaces
export interface AlertItem {
  id: string;
  alertCode: string;
  alertName: string;
  deviceName: string;
  sn: string;
  product: string;
  faultyModule: string;
  occurrences: number;
  status: "active" | "resolved";
  occuranceTime: string;
  recoveryTime: string | null;
  deviceModel: string;
  possibleReason: string;
  suggestions: string[];
}

// Alert names
const alertNames = [
  "Grid outage",
  "Battery overheating",
  "Communication failure",
  "Power output low",
  "System restart",
  "Firmware update required",
  "Inverter overload",
  "Battery low voltage",
  "Connection timeout",
  "System overheat",
  "Input power surge",
  "Battery cell imbalance",
  "Fan failure",
  "Output short circuit",
  "Grid voltage abnormal"
];

// Faulty modules
const faultyModules = [
  "Master",
  "BMS",
  "Controller",
  "Inverter",
  "System",
  "Power Module",
  "Communication Board",
  "Fan System",
  "Battery Pack",
  "PV Input"
];

// Product models
const products = [
  "Hyper2000",
  "Solar Flow 2400",
  "PowerCore 5000",
  "EnergyStation Pro",
  "SmartBattery 3.0"
];

// Device models
const deviceModels = [
  "Solar Flow 2400",
  "Hyper2000",
  "PowerBox 3000",
  "EnergyCube Max",
  "SolarStation Pro"
];

// Possible reasons
const possibleReasons = [
  "Grid power is unstable or has been disconnected.",
  "Device temperature exceeded safe operating limits due to ambient temperature or cooling system failure.",
  "Communication between internal components or with the monitoring system has been interrupted.",
  "System detected lower than expected power output from solar panels or battery system.",
  "System has detected an abnormal condition and performed an automatic restart to resolve it.",
  "Current firmware version has known issues that require an update to fix.",
  "The system is experiencing higher than rated load demand.",
  "Battery voltage has dropped below the safe operating threshold.",
  "Network connectivity issues are preventing proper communication with the monitoring server.",
  "Internal temperature sensors have detected thermal conditions outside of normal parameters."
];

// Suggestions templates
const suggestionTemplates = [
  [
    "Check if the grid power supply is stable and all connections are secure.",
    "Verify that the AC circuit breaker is in the ON position.",
    "If the grid is confirmed stable but the alert persists, contact customer support."
  ],
  [
    "Ensure the device has proper ventilation and is not exposed to direct sunlight.",
    "Check if cooling fans are operating normally and clean any dust or debris.",
    "If temperature remains high after ensuring proper ventilation, power off the system and contact technical support."
  ],
  [
    "Restart the device to re-establish communication.",
    "Check all communication cables and connections for damage or loose connections.",
    "If problem persists after restart, perform a factory reset according to the user manual."
  ],
  [
    "Check for shading or debris on solar panels that might reduce efficiency.",
    "Verify that all panels are properly connected and undamaged.",
    "If output remains low in good sunlight conditions, schedule a professional inspection."
  ],
  [
    "No action required if system resumes normal operation after restart.",
    "If restarts occur frequently, check for power quality issues or overload conditions.",
    "Document the frequency and circumstances of restarts and contact technical support if they continue."
  ]
];

// Generate a random date within a range
function randomDate(start: Date, end: Date): Date {
  return new Date(
    start.getTime() + Math.random() * (end.getTime() - start.getTime())
  );
}

// Format date to string
function formatDate(date: Date): string {
  return date.toISOString().replace("T", " ").substring(0, 19);
}

// Generate mock alerts
function generateMockAlerts(count: number): AlertItem[] {
  const alerts: AlertItem[] = [];
  const now = new Date();
  const sixMonthsAgo = new Date(
    now.getFullYear(),
    now.getMonth() - 6,
    now.getDate()
  );

  for (let i = 1; i <= count; i++) {
    // Determine if alert is active or resolved
    const isActive = i <= count * 0.4; // 40% active, 60% resolved

    // Generate occurrence time
    const occuranceTime = randomDate(sixMonthsAgo, now);

    // Generate recovery time (null for active alerts)
    const recoveryTime = isActive
      ? null
      : formatDate(randomDate(occuranceTime, now));

    // Random selections
    const alertNameIndex = Math.floor(Math.random() * alertNames.length);
    const faultyModuleIndex = Math.floor(Math.random() * faultyModules.length);
    const productIndex = Math.floor(Math.random() * products.length);
    const deviceModelIndex = Math.floor(Math.random() * deviceModels.length);
    const reasonIndex = Math.floor(Math.random() * possibleReasons.length);
    const suggestionIndex = Math.floor(
      Math.random() * suggestionTemplates.length
    );

    // Room number
    const floorNum = Math.floor(Math.random() * 5) + 1;
    const roomNum = Math.floor(Math.random() * 20) + 1;
    const roomId = `${floorNum}0${floorNum}-${roomNum.toString().padStart(2, "0")}`;

    alerts.push({
      id: `AL${i.toString().padStart(5, "0")}`,
      alertCode: ((i % 15) + 1).toString().padStart(3, "0"), // 001-015 repeating
      alertName: alertNames[alertNameIndex],
      deviceName: `Room ${roomId}`,
      sn: `100001${i.toString().padStart(8, "0")}`,
      product: products[productIndex],
      faultyModule: faultyModules[faultyModuleIndex],
      occurrences: Math.floor(Math.random() * 30) + 1,
      status: isActive ? "active" : "resolved",
      occuranceTime: formatDate(occuranceTime),
      recoveryTime: recoveryTime,
      deviceModel: deviceModels[deviceModelIndex],
      possibleReason: possibleReasons[reasonIndex],
      suggestions: suggestionTemplates[suggestionIndex]
    });
  }

  return alerts;
}

// Generate 50 mock alerts
export const mockAlerts = generateMockAlerts(50);

// Split into active and historical
export const activeAlerts = mockAlerts.filter(
  alert => alert.status === "active"
);
export const historicalAlerts = mockAlerts.filter(
  alert => alert.status === "resolved"
);

// Export default for convenience
export default {
  mockAlerts,
  activeAlerts,
  historicalAlerts
};
